package node.block;

import grammar.Lexer;
import lexical.Key;
import node.Node;
import node.decl.ConstDecl;
import node.decl.VarDecl;
import symbol.SymbolTable;

import java.util.ArrayList;

public class Block implements Node {
    private final Lexer lexer;
    private final SymbolTable table;
    private final Node father;
    public ArrayList<Node> nodes = new ArrayList<>();

    public Block(Lexer lexer, SymbolTable table, Node father) {
        this.lexer = lexer;
        this.table = table;
        this.father = father;
        parseBlock();
    }

    private void parseBlock() {
        table.addSymbolBlock();
        nodes.add(lexer.getCurWord()); // {
        while (!lexer.isWordType(0, Key.RBRACE)) {
            if (lexer.isWordType(0, Key.CONSTTK) || lexer.isWordType(0, Key.INTTK)) {
                if (lexer.isWordType(0, Key.CONSTTK) && lexer.isWordType(1, Key.INTTK)) {
                    nodes.add(new ConstDecl(lexer, table, this));
                } else if (lexer.isWordType(0, Key.INTTK)) {
                    nodes.add(new VarDecl(lexer, table, this));
                }
            } else {
                nodes.add(new Stmt(lexer, table, this));
            }
        }
        nodes.add(lexer.getCurWord()); // }
        table.subSymbolBlock(lexer.getWord(-1).lineNum);
    }

    @Override
    public Node getFather() {
        return father;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        for (Node word : nodes) {
            sb.append(word.toString());
        }
        return sb.append("<Block>\n").toString();
    }

    @Override
    public String genMidCode() {
        for (Node node : nodes) {
            node.genMidCode();
        }
        return "";
    }
}

